<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form isheader" v-if="headerShow">
        <div>
          <a-form size="small" :model="searchData" layout="inline">
            <a-form-item label="裁口排针名称" v-if="permissionStore.hasPermisson('ckpzlb.cx')">
              <a-input class="bacClass" allow-clear :style="{ width: '200px' }" placeholder="" v-model="searchData.name"
                       @press-enter="huiche"/>
            </a-form-item>
          </a-form>
        </div>
        <div>
          <Toolbar :items="pageData.btnList" @add="addHandler" @del="deleteHandler" @select="selectHandler"
                   @export="exportExcel" @import="importHandler" @excel="downloadHandler">
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18"/>
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18"/>
        </a-divider>
      </div>
    </template>

    <template #pageTabel>
      <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height: 100%; width: 100%; z-index: 999">
          <div style="width: 100%; height: 100%">
            <encapsulation-agrid ref="table1Ref" :configaggrid="configTable1"></encapsulation-agrid>
          </div>
      </a-spin>
    </template>
    <a-drawer style="z-index: 999" ok-text="保存" cancel-text="关闭" :drawer-style="{ zIndex: 9999 }"
              :mask-closable="false"
              :width="400" :ok-loading="pageData.pageLoading" :visible="pageData.showAdd" unmountOnClose @ok="sideOk"
              @cancel="addCancel">
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" layout="horizontal" :model="dataForm">
          <a-form-item label-col-flex="80px" label="名称：" field="cmdName"
                       :rules="[{ required: true, message: '名称必填' }]"
                       :validate-trigger="['blur', 'change']">
            <a-input class="bacClass" v-model="dataForm.cmdName"/>
          </a-form-item>

          <a-form-item label-col-flex="80px" label="裁口排针:" field="pinHeader">
            <a-textarea class="bacClass" v-model="dataForm.pinHeader" allow-clear/>
          </a-form-item>
          <a-form-item label-col-flex="80px" label="纱线排列:" field="arrangement">
            <a-textarea class="bacClass" v-model="dataForm.arrangement" allow-clear/>
          </a-form-item>
          <a-form-item label-col-flex="80px" label="备注：" field="remark">
            <!-- <a-textarea v-model="dataForm.remark" allow-clear/> -->
            <a-textarea class="bacClass" placeholder="" v-model="dataForm.remark" :max-length="400" allow-clear
                        show-word-limit/>
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script lang="ts">
import emitter from '@/hooks/useEventBus'
import {post} from '@/api/http'
import {usePagination, useRowKey, useRowSelection, useTable, useTableColumn} from '@/hooks/table'
import {onMounted, reactive, ref} from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import {Message, Modal} from '@arco-design/web-vue'
import {FormInstance} from '@arco-design/web-vue/es/form'
import usePermission from '@/store/modules/permission'
import filedownload from 'js-file-download'
import axios from 'axios'
import {baseURL} from '@/api/axios.config'

import {localeText} from '@/api/aggridZw'
import {pagingList} from '@/api/paging'
import {exportStyleExcel} from '@/api/Export2StyleExcel'
import {saveOrUpdateGridState as saveOrUpdateGridState01} from '@/hooks/useGridState'

interface Firm {
  name: string
  id: number
}

interface CKPzInfo {
  id: any
  remark: string
  firm: string
  // cutMouthCode: string
  cmdName: string
  pinHeader: string
  arrangement: string
  deleteState: string | number
  obsoleteState: string
  createName: string
  createTime: string
  updateName: string
  updateTime: string
}

export default {
  name: 'CKPZList',
  setup() {
    //查询
    let cxbl = ''
    const selectHandler = () => {
      page.value = 1
      cxbl = searchData.name
      doRefresh()
    }
    const table1Ref = ref<any>(null)
    const tableColumns = [
      {
        title: '序号',
        key: 'cutMouthCode',
        dataIndex: 'cutMouthCode',
        width: 150,
      },

      {
        title: '名称',
        key: 'cmdName',
        dataIndex: 'cmdName',
        width: 150,
      },
      {
        title: '备注',
        key: 'remark',
        dataIndex: 'remark',
        width: 150,
      },
      {
        title: '创建人',
        key: 'createName',
        dataIndex: 'createName',
        width: 150,
      },
      {
        title: '创建时间',
        key: 'createTime',
        dataIndex: 'createTime',
        width: 200,
      },
      {
        title: '最后修改人',
        key: 'updateName',
        dataIndex: 'updateName',
        width: 150,
      },
      {
        title: '最后修改时间',
        key: 'updateTime',
        dataIndex: 'updateTime',
        width: 200,
      },
      {
        title: '操作',
        key: 'id',
        slotName: 'action',
        width: 150,
        fixed: 'right',
      },
    ]
    let tc: any[] = tableColumns.map((o) => {
      let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
        tooltipField: o.key,
      }
      obj['width'] = 250
      if (o.slotName === 'action') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['lockPosition'] = 'right'
        obj['width'] = 90
        obj['cellRenderer'] = {
          template: `
            <a-tag class="tagCss" v-if="e" @click="a">修改</a-tag>`,
          setup(props: any) {
            const a = () => {
              editHandler(props.params.data)
            }
            return {
              e: pageData.isEdit,
              a,
            }
          },
        }
      }

      return obj
    })
    tc.unshift({
      showRowGroup: 'hide_def',
      headerName: "",
      "checkboxSelection": true,
      "headerCheckboxSelection": true,
      "pinned": "left",
      "width": 50,
      resizable: false,
      filter: false,
      sortable: false,
      minWidth: 50,
      maxWidth: 50,
      lockPosition: "left",
    })
    let configTable1 = {
      url: 'product/pdCuttingMouthNeedle/getPage', //接口路径
      queryData: {
        //接口参数
        deleteState: 0,
        cmdName: cxbl,
      },
      paginationShow: true, //分页是否显示
      invokeiIterface: true, //是否调用接
      rowMultiSelectWithClick: true, //点击行是否多选
      column: tc,
      fileName: 'CKPZList-1'
    }
    const total = ref(0)
    const page = ref(1)
    const size = ref(10)

    function PageSize(val: any) {
      page.value = val
      doRefresh()
    }

    function change1(val: any) {
      size.value = val
      doRefresh()
    }

    const headerShow = ref<boolean>(true)
    let gc = reactive([])
    const selChange = (v: any) => {
      let typeV = typeof v
      if (typeV == 'object') {
        v = ''
      }
      post({
        url: 'product/pdCuttingMouthNeedle/getCmdName',
        data: {
          key: v,
          deleteState: 0,
        },
      }).then((result: any) => {
        if (result.code === 200) {
          pageData.gcList = result.data
        }
      })
    }

    function doRefresh() {
      table1Ref.value.setQuery({
        deleteState: 0,
        cmdName: cxbl,
      })
    }

    const {selectedRowKeys, onSelectionChange} = useRowSelection()
    const pagination = usePagination(doRefresh)
    const table = useTable()
    const rowKey = useRowKey('id')
    const pageData = reactive<{
      gcList: Firm[]
      showAdd: boolean
      sideTitle: string
      rHeight: number | undefined
      btnList: any[]
      pageLoading: boolean
      isEdit: boolean
    }>({
      gcList: [],
      showAdd: false,
      sideTitle: '新增裁口排针资料',
      rHeight: 0,
      btnList: [],
      pageLoading: false,
      isEdit: false,
    })

    onMounted(() => {
      // 切换tap到本页面执行的方法
      emitter.on('CKPZList', () => {
        // selCxAll({});
        doRefresh()
      })
    })
    const queryData = reactive({
      firm: '',
      clothType: '',
    })
    const addHandler = () => {
      for (const key in dataForm) {
        if (key == 'id') {
          dataForm.id = null
        } else {
          dataForm[key] = ''
        }
      }
      pageData.showAdd = true
      pageData.sideTitle = '新增裁口排针资料'
    }
    const searchData = reactive({
      // cutMouthCode: '',
      name: '',
    })

    // 表格准备事件
    const colState = ref()
    const gridOption = ref()
    const gridReady = (params: any) => {
      gridOption.value = params.api
      colState.value = params.columnApi
      //gridOption.value.sizeColumnsToFit();
    }

    const dataForm = reactive<CKPzInfo>({
      id: null,
      remark: '',
      firm: '',
      // cutMouthCode: '',
      cmdName: '',
      pinHeader: '',
      arrangement: '',
      deleteState: '',
      obsoleteState: '',
      createName: '',
      createTime: '',
      updateName: '',
      updateTime: '',
    })
    const formRef = ref<FormInstance>()
    const sideOk = () => {
      formRef.value?.validate().then((err) => {
        pageData.pageLoading = true
        if (!err) {
          if (pageData.sideTitle === '新增裁口排针资料') {
            post({
              url: 'product/pdCuttingMouthNeedle/insert',
              data: [dataForm],
            })
                .then((res: any) => {
                  if (res.code === 200) {
                    formRef.value?.resetFields()
                    pageData.showAdd = false
                    Message.success({
                      content: '新增成功',
                      duration: 5000,
                    })
                    doRefresh()
                  } else {
                    Message.error({
                      content: res.message,
                      duration: 5000,
                    })
                  }
                })
                .finally(() => {
                  pageData.pageLoading = false
                })
          } else {
            post({
              url: 'product/pdCuttingMouthNeedle/update',
              data: [dataForm],
            })
                .then((res: any) => {
                  if (res.code === 200) {
                    formRef.value?.resetFields()
                    pageData.showAdd = false
                    Message.success({
                      content: '修改成功',
                      duration: 5000,
                    })
                    doRefresh()
                  } else {
                    Message.error({
                      content: res.message,
                      duration: 5000,
                    })
                  }
                })
                .finally(() => {
                  pageData.pageLoading = false
                })
          }
        }
      })
    }
    const deleteHandler = () => {
      if (table1Ref.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
      }
      Modal.confirm({
        title: '系统提示',
        content: '确认删除选中的数据?',
        draggable: true,
        onOk() {
          pageData.pageLoading = true
          post({
            url: 'product/pdCuttingMouthNeedle/delete',
            data: table1Ref.value.getSelectedRows().map((o: any) => {
              return o.id
            }),
          })
              .then(({code, data}: any) => {
                if (code === 200) {
                  Message.success({
                    content: '删除成功',
                    duration: 5000,
                  })
                } else {
                  Message.success({
                    content: '修改失败',
                    duration: 5000,
                  })
                }
              })
              .finally(() => {
                doRefresh()
                pageData.pageLoading = false
              })
        },
      })
    }
    const editHandler = (record: CKPzInfo) => {
      dataForm.id = record.id
      dataForm.arrangement = record.arrangement
      dataForm.cmdName = record.cmdName
      // dataForm.cutMouthCode = record.cutMouthCode
      dataForm.firm = record.firm
      dataForm.remark = record.remark
      dataForm.pinHeader = record.pinHeader
      pageData.sideTitle = '修改裁口排针资料'
      pageData.showAdd = true
    }
    const addCancel = () => {
      Object.keys(dataForm).forEach((o) => (dataForm[o] = ''))
      pageData.showAdd = false
    }

    //前端导出
    function exportExcel() {
      if (table1Ref.value.getSelectedRows().length === 0) {
        Message.error('请先勾选需导出行数据！')
        return
      }
      const header = ['序号', '名称', '备注', '创建人', '创建时间', '最后修改人', '最后修改时间']
      const filterVal = ['cutMouthCode', 'cmdName', 'remark', 'createName', 'createTime', 'updateName', 'updateTime']
      let data = formatJson(filterVal, table1Ref.value.getSelectedRows());
      exportStyleExcel({header, data, filename: "裁口排针.xlsx"})
    }

    function formatJson(filterVal: any[], jsonData: any[]) {
      return jsonData.map(v => filterVal.map(j => {
        if (v[j]) {
          return v[j];
        } else {
          return '';
        }
      }))
    }

    //模板下载
    const downloadHandler = () => {
      axios
          .get(baseURL + '/product/pdCuttingMouthNeedle/uploadCutMouthModel', {
            responseType: 'blob',
            headers: {
              token: sessionStorage.getItem('USER-TOKEN-KEY'),
            },
          })
          .then((res) => {
            if (res.status === 200) {
              filedownload(res.data, '裁口排针.xlsx')
            }
          })
    }
    //导入
    const importHandler = () => {
      const inputEle: HTMLInputElement = document.createElement('input')
      inputEle.type = 'file'
      inputEle.id = 'fileUploadExcel'
      inputEle.accept =
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
      inputEle.addEventListener('change', (e) => {
        const formData = new FormData()
        if (inputEle.files !== null) {
          formData.append('file', inputEle.files[0] || '')
        } else {
          Message.warning('未选择文件！')
          return
        }
        pageData.pageLoading = true
        axios
            .post(baseURL + '/product/pdCuttingMouthNeedle/analyseCutMouthModel', formData, {
              headers: {
                'Content-Type': 'multipart/form-data',
                token: sessionStorage.getItem('USER-TOKEN-KEY'),
              },
            })
            .then((result) => {
              if (result.data['code'] === 200) {
                Message.success('导入成功')
              } else {
                Message.error(result.data.message)
              }
            })
            .finally(() => {
              pageData.pageLoading = false
              doRefresh()
            })
      })
      inputEle.click()
    }
    //设置权限
    // ['查询', '新增', '删除', '导出', '导入']
    const permissionStore = usePermission()

    if (permissionStore.hasPermisson('ckpzlb.cx')) {
      pageData.btnList.push('查询')
    }
    if (permissionStore.hasPermisson('ckpzlb.xz')) {
      pageData.btnList.push('新增')
    }
    if (permissionStore.hasPermisson('ckpzlb.sc')) {
      pageData.btnList.push('删除')
    }
    if (permissionStore.hasPermisson('ppzl.dc')) {
      pageData.btnList.push('导出')
    }
    if (permissionStore.hasPermisson('ppzl.dr')) {
      pageData.btnList.push('导入')
    }
    if (permissionStore.hasPermisson('ckpzlb.mbxz')) {
      pageData.btnList.push('模板下载')
    }
    if (permissionStore.hasPermisson('ckpzlb.xg')) {
      pageData.isEdit = true
    }
    const handleChange = (_data: any) => {
      table.handleSuccess(_data)
    }
    const defaultColDef = {
      sortable: true,
      resizable: true,
      filter: true,
      // flex: 1
    }
    const localeText1: any = ref(localeText)
    const huiche = () => {
      page.value = 1
      cxbl = searchData.name
      doRefresh()
    }
    const pagingList1: any = ref(pagingList)
    return {
      colState,
      pagingList1,
      huiche,
      localeText1,
      defaultColDef,
      tc,
      total,
      PageSize,
      change1,
      page,
      size,
      // ci,
      selChange,
      addCancel,
      searchData,
      editHandler,
      deleteHandler,
      sideOk,
      formRef,
      dataForm,
      addHandler,
      exportExcel,
      importHandler,
      downloadHandler,
      selectedRowKeys,
      pagination,
      tableColumns,
      table,
      rowKey,
      pageData,
      queryData,
      selectHandler,
      gc,
      headerShow,
      handleChange,
      gridReady,
      permissionStore,
      table1Ref,
      configTable1
    }
  },
  components: {Toolbar, },
}
</script>
